<template>
  <div class="padding-lr20 auth">
    <van-form @submit="onSubmit">
      <div
        style="color: #ccc;font-size: 11px;text-align: center;padding-top: 10px;"
      >--------------- 以下为必填项 ---------------</div>
      <van-field
        v-model="params.enterprise_name"
        :disabled="status == 1"
        name="enterprise_name"
        label="企业名称"
        placeholder="企业名称"
      />
      <van-field
        v-model="params.company_code"
        :disabled="status == 1"
        name="company_code"
        label="企业信用代码"
        placeholder="企业信用代码"
      />
      <van-field name="business_license" :disabled="status == 1" label="营业执照副本">
        <template #input>
          <van-uploader
            :disabled="status == 1"
            max-count="1"
            :after-read="afterRead1"
            v-model="img1_list"
          />
        </template>
      </van-field>
      <van-field name="live_photo" :disabled="status == 1" label="实景照">
        <template #input>
          <van-uploader
            :disabled="status == 1"
            max-count="1"
            :after-read="afterRead3"
            v-model="img3_list"
          />
        </template>
      </van-field>
      <div
        style="color: #ccc;font-size: 11px;text-align: center;padding-top: 10px;"
      >--------------- 以下为选填项 ---------------</div>
      <van-field
        :disabled="status == 1"
        readonly
        clickable
        name="term_time"
        v-model="params.term_time"
        label="有效期"
        placeholder="点击选择有效期"
        @click="status == 1 ? '' : showCalendar = true"
      />
      <van-calendar v-model="showCalendar" @confirm="onConfirm" />
      <van-field
        v-model="params.apply_name"
        :disabled="status == 1"
        name="apply_name"
        label="申请人姓名"
        placeholder="申请人姓名"
      />
      <van-field
        :disabled="status == 1"
        v-model="params.apply_card"
        name="apply_card"
        label="申请人身份证号码"
        placeholder="申请人身份证号码"
      />
      <van-field name="holding_card" :disabled="status == 1" label="手持身份证照">
        <template #input>
          <van-uploader
            :disabled="status == 1"
            max-count="1"
            :after-read="afterRead2"
            v-model="img2_list"
          />
        </template>
      </van-field>
      <van-field
        v-model="params.legal_person"
        :disabled="status == 1"
        name="legal_person"
        label="法人代表"
        placeholder="法人代表"
      />

      <div>
        <!-- 未认证 -->
        <van-button block class="btn" v-if="status == 0" native-type="submit">保存</van-button>
        <!-- 驳回 -->
        <van-button block class="btn" v-if="status == 3" native-type="submit">重新提交</van-button>
        <!-- 审核中 -->
        <van-button block class="btn" disabled v-if="status == 1">审核中</van-button>
        <!-- 审核成功 -->
        <van-button block class="btn" disabled v-if="status == 2">审核成功</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      showCalendar: false,

      img1_list: [],
      img2_list: [],
      img3_list: [],

      status: 0,

      params: {
        enterprise_name: "", // enterprise_title
        company_code: "",
        business_license: "",
        term_time: "",
        apply_name: "", // enterprise_name
        apply_card: "",
        holding_card: "",
        legal_person: "",
        live_photo: ""
      }
    };
  },
  mounted() {
    document.querySelector("html").style.backgroundColor = "#ffffff";
    this.authStatus();

    this.$axios
      .post("/home/entInfo", {
        token: localStorage.getItem("qx_token")
      })
      .then(res => {
        this.params.enterprise_name = res.data.data.info["enterprise_title"];
        this.params.apply_name = res.data.data.info["enterprise_name"];
      });
  },
  methods: {
    onConfirm(date) {
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      var d = date.getDate();
      var h = date.getHours();
      var min = date.getMinutes();
      var s = date.getSeconds();
      var str =
        y +
        "-" +
        (m < 10 ? "0" + m : m) +
        "-" +
        (d < 10 ? "0" + d : d) +
        " " +
        (h < 10 ? "0" + h : h) +
        ":" +
        (min < 10 ? "0" + min : min) +
        ":" +
        (s < 10 ? "0" + s : s);
      this.params.term_time = str;
      this.showCalendar = false;
    },
    imgcompress(file, files, name, list) {
      let quality = 0.6;
      const img = document.createElement("img");
      const reader = new FileReader(); // 读取文件资源实例
      reader.readAsDataURL(file); //读取图片资源
      reader.onload = e => {
        //读取成功
        img.src = e.target.result;
        setTimeout(() => {
          const { width: originWidth, height: originHeight } = img; //上传的图片的宽高
          const maxWidth = 1000, //设置一个canvas 的最大宽高
            maxHight = 1000;
          if (originWidth > maxWidth || originHeight > maxHight) {
            //计算出图片的缩放比例
            if (originWidth > originHeight) {
              //宽 大于 高
              const Proportion = Math.ceil(originWidth / maxWidth);
              let targetWidht = parseInt(originWidth / Proportion); //目标的宽度
              let targetHeight = parseInt(originHeight / Proportion); //目标的高度

              this.createCanvasCompress(
                targetWidht,
                targetHeight,
                img,
                files,
                quality,
                name,
                list
              );
            } else {
              const Proportion = Math.ceil(originHeight / maxHight); //高大于宽
              let targetWidht = parseInt(originWidth / Proportion); //目标的宽度
              let targetHeight = parseInt(originHeight / Proportion); //目标的高度
              let bold = this.createCanvasCompress(
                targetWidht,
                targetHeight,
                img,
                files,
                quality,
                name,
                list
              );
            }
          } else {
            this.createCanvasCompress(
              originWidth,
              originHeight,
              img,
              files,
              quality,
              name,
              list
            );
          }
        }, 1500);
      };
    },
    createCanvasCompress(
      targetWidth,
      targetHeight,
      img,
      files,
      quality,
      name,
      list
    ) {
      let that = this;
      return new Promise((resolve, reject) => {
        const canvas = document.createElement("canvas");
        const context = canvas.getContext("2d");
        // 设置宽高度为等同于要压缩图片的尺寸
        canvas.width = targetWidth;
        canvas.height = targetHeight;
        context.clearRect(0, 0, targetWidth, targetHeight);
        //将img绘制到画布上
        console.log(targetWidth, targetHeight);
        context.drawImage(img, 0, 0, targetWidth, targetHeight);

        let bold = canvas.toBlob(
          function(blob) {
            resolve(blob);
            const formData = new FormData();
            formData.append("file", blob, "1.jpg");
            formData.append("type", "8");
            let config = {
              headers: { "Content-Type": "multipart/form-data" }
            };
            that.$axios
              .post("/common/upload/image/qiniu", formData, config)
              .then(res => {
                if (res.data.code == 0) {
                  that.params[name] = res.data.url;
                  that[list] = [{ url: res.data.url }];
                  files.status = "done";
                  files.message = "上传成功";
                } else {
                  file.status = "failed";
                  file.message = "上传失败1";
                }
              })
              .catch(err => {
                console.log(err);
                files.status = "failed";
                files.message = "上传失败2";
              });
          },
          "image/png",
          quality
        );
      });
      // 创建画布
    },
    afterRead1(file) {
      let that = this;
      file.status = "uploading";
      file.message = "上传中...";

      let maxSize = 1 * 1024 * 1024; //自己定义的文件大小，超过1M就开始压缩
      let fileObj = file.file; // 当前的图片

      // 如果是heic格式图片
      if (fileObj.name.split(".")[1] == "heic") {
        heic2any({
          blob: fileObj,
          toType: "image/jpg"
        })
          .then(function(res) {
            let files = new window.File([res], fileObj.name, {
              type: fileObj.type
            });
            that.imgcompress(files, file, "business_license", "img1_list");
          })
          .catch(function(x) {
            console.log(x);
          });
        return false;
      }

      // 正常格式  大于限制、不大于限制
      if (fileObj.size > maxSize) {
        this.imgcompress(fileObj, file, "business_license", "img1_list");
      } else {
        let param = new FormData();
        param.append("file", file.file);
        param.append("type", "8");
        let config = {
          headers: { "Content-Type": "multipart/form-data" }
        };
        this.$axios
          .post("/common/upload/image/qiniu", param, config)
          .then(res => {
            if (res.data.code == 0) {
              this.params.business_license = res.data.url;
              file.status = "done";
              file.message = "上传成功";
            } else {
              file.status = "failed";
              file.message = "上传失败";
            }
          });
      }
    },
    afterRead2(file) {
      let that = this;
      file.status = "uploading";
      file.message = "上传中...";

      let maxSize = 1 * 1024 * 1024; //自己定义的文件大小，超过1M就开始压缩
      let fileObj = file.file; // 当前的图片

      // 如果是heic格式图片
      if (fileObj.name.split(".")[1] == "heic") {
        heic2any({
          blob: fileObj,
          toType: "image/jpg"
        })
          .then(function(res) {
            let files = new window.File([res], fileObj.name, {
              type: fileObj.type
            });
            that.imgcompress(files, file, "holding_card", "img2_list");
          })
          .catch(function(x) {
            console.log(x);
          });
        return false;
      }

      // 正常格式  大于限制、不大于限制
      if (fileObj.size > maxSize) {
        this.imgcompress(fileObj, file, "holding_card", "img2_list");
      } else {
        let param = new FormData();
        param.append("file", file.file);
        param.append("type", "8");
        let config = {
          headers: { "Content-Type": "multipart/form-data" }
        };
        this.$axios
          .post("/common/upload/image/qiniu", param, config)
          .then(res => {
            if (res.data.code == 0) {
              this.params.holding_card = res.data.url;
              file.status = "done";
              file.message = "上传成功";
            } else {
              file.status = "failed";
              file.message = "上传失败";
            }
          });
      }
    },
    afterRead3(file) {
      let that = this;
      file.status = "uploading";
      file.message = "上传中...";

      let maxSize = 1 * 1024 * 1024; //自己定义的文件大小，超过1M就开始压缩
      let fileObj = file.file; // 当前的图片

      // 如果是heic格式图片
      if (fileObj.name.split(".")[1] == "heic") {
        heic2any({
          blob: fileObj,
          toType: "image/jpg"
        })
          .then(function(res) {
            let files = new window.File([res], fileObj.name, {
              type: fileObj.type
            });
            that.imgcompress(files, file, "live_photo", "img3_list");
          })
          .catch(function(x) {
            console.log(x);
          });
        return false;
      }

      // 正常格式  大于限制、不大于限制
      if (fileObj.size > maxSize) {
        this.imgcompress(fileObj, file, "live_photo", "img3_list");
      } else {
        let param = new FormData();
        param.append("file", file.file);
        param.append("type", "8");
        let config = {
          headers: { "Content-Type": "multipart/form-data" }
        };
        this.$axios
          .post("/common/upload/image/qiniu", param, config)
          .then(res => {
            if (res.data.code == 0) {
              this.params.live_photo = res.data.url;
              file.status = "done";
              file.message = "上传成功";
            } else {
              file.status = "failed";
              file.message = "上传失败";
            }
          });
      }
    },
    onSubmit(e) {
      if (this.params["enterprise_name"] == "") {
        this.$toast("请填写企业名称");
        return false;
      }
      if (this.params["company_code"] == "") {
        this.$toast("请填写企业信用代码");
        return false;
      }
      if (this.img1_list.length == 0) {
        this.$toast("请上传营业执照副本");
        return false;
      }
      // if (this.img2_list.length == 0) {
      //   this.$toast("请上传手持身份证照");
      //   return false;
      // }
      if (this.img3_list.length == 0) {
        this.$toast("请上传实景照");
        return false;
      }

      this.params.token = localStorage.getItem("qx_token");
      this.$axios.post("/home/submitEntauth", this.params).then(res => {
        console.log(res);
        if (res.data.code == 0) {
          this.$toast(res.data.msg);
          this.$router.go(-1);
        }
      });
    },
    // 认证状态
    authStatus() {
      this.$axios
        .post("/home/entCertification", {
          token: localStorage.getItem("qx_token")
        })
        .then(res => {
          let data = res.data.data;
          if (!data.id) {
            this.status = 0;
            console.log("未审核");
          } else if (data.id && data.status == 0) {
            this.status = 1;
            console.log("审核中");
            data.term_time = data.term_time ? data.term_time : "";
            this.params = data;
            this.img1_list = [{ url: data.business_license }];
            this.img2_list = [{ url: data.holding_card }];
            this.img3_list = [{ url: data.live_photo }];
          } else if (data.status == 1) {
            this.status = 2;
            console.log("审核成功");
            data.term_time = data.term_time ? data.term_time : "";
            this.params = data;
            this.img1_list = [{ url: data.business_license }];
            this.img2_list = [{ url: data.holding_card }];
            this.img3_list = [{ url: data.live_photo }];
          } else if (data.status == -1) {
            this.status = 3;
            console.log("驳回");
            data.term_time = data.term_time ? data.term_time : "";
            this.params = data;
            this.img1_list = [{ url: data.business_license }];
            this.img2_list = [{ url: data.holding_card }];
            this.img3_list = [{ url: data.live_photo }];
          }
        });
    }
  }
};
</script>
<style>
html {
  background-color: white;
}
.auth .van-cell {
  padding-left: 0;
  padding-right: 0;
}
.auth .van-cell:nth-of-type(5):after {
  border-bottom: 0 !important;
}
</style>
<style scoped>
.item_li {
  padding: 0.1rem 0;
  line-height: 0.8rem;
  border-bottom: 1px solid #f0f0f0;
  font-size: 18px;
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: center;
}
.item_left {
  line-height: 0.8rem;
  height: 0.8rem;
}
.item_left_t {
  min-width: 1.4rem;
  display: inline-block;
  font-size: 0.28rem;
}
.item_right {
  flex-grow: 1;
}

.item_li input {
  height: 0.5rem;
  background: no-repeat;
  width: 100%;
  outline: 0;
  font-size: 0.28rem;
}
textarea {
  width: 100%;
  height: auto;
  min-height: 40px;
  line-height: 40px;
}
.btn {
  background: #fe0000;
  color: white;
  border-radius: 4px;
  margin: 0.6rem 0;
}
</style>
